package top.dj.jdbc.routing.component;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import top.dj.jdbc.routing.ClientDataSource;
import top.dj.jdbc.routing.ClientDataSourceContextHolder;
import top.dj.jdbc.routing.annotation.DataSourceRouting;

/**
 * Aspect that will mark a method to route to the desired datasource before calling the method.
 *
 * @Author: DengJia
 * @Date: 2021/9/27 9:13
 * @Description: 创建 DataSourceRoutingAspect，来处理注解 DataSourceRouting
 */

@Aspect
@Component
@Slf4j
public class DataSourceRoutingAspect {

    @Around("@annotation(dataSourceRouting)")
    public Object aroundDataSourceRouting(ProceedingJoinPoint joinPoint, DataSourceRouting dataSourceRouting) throws Throwable {
        ClientDataSource previousClient = ClientDataSourceContextHolder.getClientDatabase();
        log.warn("Setting clientDatabase {} into DataSourceContext", dataSourceRouting.value());
        ClientDataSourceContextHolder.set(dataSourceRouting.value());

        try {
            return joinPoint.proceed();
        } finally {
            if (previousClient != null) {
                // 在执行方法后将上下文恢复到以前的状态
                ClientDataSourceContextHolder.set(previousClient);
            } else {
                // 没有值被设置到上下文之前，只是清除上下文
                // 防止内存泄漏
                ClientDataSourceContextHolder.clear();
            }
        }
    }
}
